package com.tensquare.manager.filter;

import cn.hutool.core.util.StrUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.protocol.RequestContent;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class ManagerFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        if (request.getMethod().equals("OPTIONS")){ //因为当我们发送请求到网关时是两次请求，此方法（OPTIONS）需要放行
            return null;
        }
        if (request.getRequestURI().contains("/login")){
            return null;
        }
        String header = request.getHeader("Authorization");
        if (StrUtil.isNotEmpty(header)){
            System.out.println("header = " + header);
            currentContext.addZuulRequestHeader("Authorization",header);
            return null;
        }
        currentContext.setSendZuulResponse(false);  //不再继续执行
        currentContext.setResponseStatusCode(403);  //设置响应的状态码是403或401
        currentContext.setResponseBody("无权访问!");//设置响应体内容
        currentContext.getResponse().setContentType("text/html;charset=utf-8"); //设置响应的内容类型
        return null;
    }
}
